package com.zcsy.manage.web.property;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.model.RequestConstants;
import com.zcsy.commons.model.RequestJson;
import com.zcsy.commons.util.DateUtils;
import com.zcsy.manage.model.base.CellHouse;
import com.zcsy.manage.model.base.CellInfo;
import com.zcsy.manage.model.property.FeeBill;
import com.zcsy.manage.model.property.FeeBillDetail;
import com.zcsy.manage.model.system.Dict;
import com.zcsy.manage.model.system.User;
import com.zcsy.manage.service.base.ICellHouseService;
import com.zcsy.manage.service.base.ICellInfoService;
import com.zcsy.manage.service.property.IFeeBillDetailService;
import com.zcsy.manage.service.system.IDictService;
import com.zcsy.manage.web.common.LogUtils;
import com.zcsy.manage.web.tools.JExcelReport;

/**
 * @Title: FeeBillDetailController.java
 * @Package： com.zcsy.manage.web.property
 * @Description: 物业账单详情控制层管理类
 * @author xujl
 * @Copyright: 2015 武汉中财数元信息技术有限公司 All rights reserved.
 * @date 2016年4月14日
 * @version 1.0
 * @see JDK1.7.0_75
 * @since
 */
@Controller
@RequestMapping(value = "/feeBillDetail")
public class FeeBillDetailController {

    @Autowired
    private IFeeBillDetailService detailService;

    @Autowired
    private IDictService dictService;

    @Autowired
    private ICellInfoService cellInfoService;

    @Autowired
    private ICellHouseService cellHouseService;

    private final static int NONEEDING = 0;//发票类型：无
    private final static int PERSONAL = 1;//发票类型：个人
    private final static int UNIT     = 2;//发票类型：单位
    
    /**
     * @Description 根据查询条件分页获取账单详情数据列表
     * @param model
     * @param pNo
     *            当前页
     * @param cellId
     *            小区id
     * @param regionId
     *            区域id
     * @param buildingId
     *            楼栋id
     * @param unitId
     *            单元id
     * @param houseId
     *            房屋id
     * @param req
     *            用户的请求
     * @return 返回的结果
     * @author xujl
     * @date 2016年4月19日
     * @see
     */
    @RequestMapping(value = "detailList", method = RequestMethod.GET)
    public String detailList(Model model, Integer pNo, Integer pSize, String billId,
                             Integer payWay, String beginTime, String endTime,
                             HttpServletRequest req) {
        if (pNo == null) {
            pNo = Constants.PAGE_NO;
        }

		Integer pageSize;
		if (pSize == null) {
			pageSize = Constants.PAGE_SIZE;
		} else {
			switch (pSize) {
				case 0: pageSize = Constants.PAGE_SIZE;
				break;
				case 1: pageSize = Constants.PAGE_SIZE_TWENTY;
				break;
				case 2: pageSize = Constants.PAGE_SIZE_FIFTY;
				break;
				default:pageSize = Constants.PAGE_SIZE;
				break;
			}
		}
		
        // 此处添加PageHelper将会走拦截器，进行分页，分页方法只针对紧跟着PageHelper的查询方法有效
        PageHelper.startPage(pNo, pageSize);

        FeeBillDetail record = new FeeBillDetail();

        //获取当前小区id
        User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        String cellId = user.getCurrentCell().getId();
        record.setCellId(cellId);
        
        // 标题不为空时，设置标题
        if (StringUtils.isNotEmpty(billId)) {
            record.setBillId(billId);
        }
        if (StringUtils.isNotEmpty(beginTime)) {
            record.setStartTime(beginTime);
        }
        if (StringUtils.isNotEmpty(endTime)) {
            record.setEndTime(endTime);
        }
        record.setPayWay(Constants.PAY_WAY_HOUTAI);

        List<FeeBill> detailList = detailService.selectByKeyword(record);
        PageInfo<FeeBill> info = new PageInfo<FeeBill>(detailList);
        
        model.addAttribute("detailInfo", info);
        model.addAttribute("currentPage", pNo);
		model.addAttribute("pSize", pSize);
        model.addAttribute("cellId", cellId);
        model.addAttribute("billId", billId);
        model.addAttribute("payWay", payWay);
        model.addAttribute("beginTime", beginTime);
        model.addAttribute("endTime", endTime);

        // 从缓存不为空则从缓存中获取通知类型，为空则从数据字典获取
        List<Dict> payList = dictService.getDictFromCache("payWay");
        model.addAttribute("payWays", payList);

//        List<CellInfo> cellInfos = cellInfoService.getAllCellInfo();
//        model.addAttribute("cellInfos", cellInfos);

		List<Dict> pageSizes = dictService.getDictFromCache("pageSize");
		model.addAttribute("pageSizes", pageSizes);

        return "property/feebilldetail/billDetailList";
    }

    /**
     * @Description 编辑保修问题<br>
     * @param id
     *            主键id
     * @return 跳转画面URL
     * @author xujl
     * @date 2016年4月14日
     * @see
     */
    @RequestMapping(value = "gotoDetail", method = RequestMethod.GET)
    public String gotoDetail(Model model, String id, String houseId, String type) {

        String url = "";
        try {

            List<Dict> payList = dictService.getDictFromCache("payWay");
            model.addAttribute("payWays", payList);

            CellHouse house = cellHouseService.selectByPrimaryKey(houseId);
            FeeBillDetail detail = detailService.selectByPrimaryKey(id);
            
            CellHouse cellHouse = cellHouseService.selectByPrimaryKey(houseId);
            
            model.addAttribute("house", house);
            model.addAttribute("detail", detail);
            model.addAttribute("type", type);
            model.addAttribute("cellHouse", cellHouse);
            url = "property/feebilldetail/detailInfo";

        } catch (Exception e) {
        }
        return url;
    }

    /**
     * @Description 根据多个id详情信息<br>
     * @param iDs
     *            多个id
     * @param req
     *            用户请求
     * @return 请求结果
     * @author xujl
     * @date 2016年4月14日
     * @see
     */
    @RequestMapping(value = "deleteInfo", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson deleteInfo(String iDs, HttpServletRequest req) {

        RequestJson result = new RequestJson();
        User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        try {
            String ids[] = iDs.split("\\,");
            for (int i = 0; i < ids.length; i++ ) {
                detailService.deleteByPrimaryKey(ids[i]);
            }
            result.setSuccess(true);
            LogUtils.insertLog("用户删除账单详情", user.getId(), req);
        } catch (NumberFormatException e) {
            result.setSuccess(false);
            result.setMsg("操作失败");
        }
        return result;
    }

    /**
     * @Description 根据查询条件分页获取已删除的账单详情数据列表
     * @param model
     * @param pNo
     *            当前页
     * @param cellId
     *            小区id
     * @param regionId
     *            区域id
     * @param buildingId
     *            楼栋id
     * @param unitId
     *            单元id
     * @param houseId
     *            房屋id
     * @param req
     *            用户的请求
     * @return 返回的结果
     * @author xujl
     * @date 2016年4月19日
     * @see
     */
    @RequestMapping(value = "delList", method = RequestMethod.GET)
    public String delList(Model model, Integer pNo, Integer pSize, String billId, String cellId, Integer payWay,
                          String beginTime, String endTime, HttpServletRequest req) {
        
        User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        cellId = user.getCurrentCell().getId();
        if (pNo == null) {
            pNo = Constants.PAGE_NO;
        }

		Integer pageSize;
		if (pSize == null) {
			pageSize = Constants.PAGE_SIZE;
		} else {
			switch (pSize) {
				case 0: pageSize = Constants.PAGE_SIZE;
				break;
				case 1: pageSize = Constants.PAGE_SIZE_TWENTY;
				break;
				case 2: pageSize = Constants.PAGE_SIZE_FIFTY;
				break;
				default:pageSize = Constants.PAGE_SIZE;
				break;
			}
		}
		
        // 此处添加PageHelper将会走拦截器，进行分页，分页方法只针对紧跟着PageHelper的查询方法有效
        PageHelper.startPage(pNo, pageSize);

        FeeBillDetail record = new FeeBillDetail();

        // 标题不为空时，设置标题
        if (StringUtils.isNotEmpty(cellId)) {
            record.setCellId(cellId);
        }
        if (StringUtils.isNotEmpty(billId)) {
            record.setBillId(billId);
        }
        if (StringUtils.isNotEmpty(beginTime)) {
            record.setStartTime(beginTime);
        }
        if (StringUtils.isNotEmpty(endTime)) {
            record.setEndTime(endTime);
        }
        record.setPayWay(Constants.PAY_WAY_HOUTAI);
        record.setState(Constants.DEL_STATE);

        List<FeeBill> detailList = detailService.selectByKeyword(record);
        PageInfo<FeeBill> info = new PageInfo<FeeBill>(detailList);

        model.addAttribute("detailInfo", info);
        model.addAttribute("currentPage", pNo);
		model.addAttribute("pSize", pSize);
        model.addAttribute("cellId", cellId);
        model.addAttribute("billId", billId);
        model.addAttribute("payWay", payWay);
        model.addAttribute("beginTime", beginTime);
        model.addAttribute("endTime", endTime);

        // 从缓存不为空则从缓存中获取通知类型，为空则从数据字典获取
        List<Dict> payList = dictService.getDictFromCache("payWay");
        model.addAttribute("payWays", payList);

        List<CellInfo> cellInfos = cellInfoService.getAllCellInfo();
        model.addAttribute("cellInfos", cellInfos);

		List<Dict> pageSizes = dictService.getDictFromCache("pageSize");
		model.addAttribute("pageSizes", pageSizes);

        return "property/delbill/delDetailList";
    }

    /**
     * @Description 导出物业费清单<br>
     * @param response
     * @author xujl
     * @date 2016年5月3日
     * @see
     */
    @RequestMapping("/exportFeeBillExcel")
    @ResponseBody
    public void exportFeeBillExcel(String beginTime, String endTime,
            HttpServletRequest request, HttpServletResponse response) {
        List<FeeBill> detailList;
        FeeBillDetail record = new FeeBillDetail();
        
        final HttpSession session = request.getSession();
        User user = (User)session.getAttribute(RequestConstants.USER_SESSION_ID);
        CellInfo cellInfo = user.getCurrentCell();
        record.setCellId(cellInfo.getId());

        if (StringUtils.isNotEmpty(beginTime)) {
            record.setStartTime(beginTime);
        }
        if (StringUtils.isNotEmpty(endTime)) {
            record.setEndTime(endTime);
        }
        record.setPayWay(Constants.PAY_WAY_HOUTAI);
        
        try {
            // 得到导出的数据列表
            detailList = detailService.selectByKeyword(record);

            // 将订单对象转化为到处所需要的数据格式
            if (detailList.size() > 0) {
                ArrayList<ArrayList<String>> dataList = new ArrayList<ArrayList<String>>();
                int index = 1;
                for (FeeBill bill : detailList) {
                    ArrayList<String> temp = new ArrayList<String>();
                    // 序号
                    temp.add(String.valueOf(index++ ));
                    temp.add(bill.getId());
                    temp.add(bill.getCellName());
                    temp.add(bill.getRegionName());
                    temp.add(bill.getBuildingName());
                    temp.add(bill.getUnitName());
                    temp.add(bill.getHouseName());
                    temp.add(DateUtils.formatDate(bill.getPayTime()));
                    temp.add(bill.getMoney().toString());
                    dataList.add(temp);
                }
                // 导出标题列
                String[] rows = new String[] {"序号", "账单号", "小区名", "区域名", "楼栋名", "单元名", "房间号",
                    "缴费时间",  "缴费金额"};
                // 导出excel文件每列宽度
                int[] style = new int[] {5, 20, 20, 20, 20, 20, 20, 20,20};
                // Excel文件sheet名称
                String sheetName = "物业费缴费记录" + DateUtils.getCurrentDate();
                String fileName = "物业费缴费记录";
                doExecl(response, fileName, sheetName, dataList, rows, style);
                LogUtils.insertLog("用户导出物业缴费记录", user.getId(), request);
            }
        } catch (Exception e) {
            return;
        }
    }
   
    /**
     * @description 导出账单的发票
     * @author chenxin
     * @date 2016年8月24日下午2:07:15
     */
    @RequestMapping("/exportBillExcel")
    @ResponseBody
    public void exportBillExcel(String beginTime, String endTime,HttpServletRequest request,
            HttpServletResponse response) {
        List<FeeBill> detailList;
        FeeBillDetail record = new FeeBillDetail();

        final HttpSession session = request.getSession();
        User user = (User)session.getAttribute(RequestConstants.USER_SESSION_ID);
        CellInfo cellInfo = user.getCurrentCell();
        record.setCellId(cellInfo.getId());
        
        if (StringUtils.isNotEmpty(beginTime)) {
            record.setStartTime(beginTime);
        }
        if (StringUtils.isNotEmpty(endTime)) {
            record.setEndTime(endTime);
        }
        record.setPayWay(Constants.PAY_WAY_HOUTAI);
        try {
            // 得到导出的数据列表
            detailList = detailService.selectByKeyword(record);

            // 将订单对象转化为到处所需要的数据格式
            if (detailList.size() > 0) {
                ArrayList<ArrayList<String>> dataList = new ArrayList<ArrayList<String>>();
                int index = 1;
                String tempString = "";
                for (FeeBill bill : detailList) {
                    String billNumber = bill.getBillNo();
                    if(!StringUtils.isNotEmpty(billNumber)){
                        FeeBillDetail feeBillDetail = detailService.selectByPrimaryKey(bill.getId());
                        feeBillDetail.setBillNo("未填写");
                        feeBillDetail.setBillTitle("未填写");
                        feeBillDetail.setBillType(NONEEDING);
                        detailService.updateByPrimaryKey(feeBillDetail);
                    }
                }
                for (FeeBill bill : detailList) {
                    ArrayList<String> temp = new ArrayList<String>();
                    // 序号
                    temp.add(String.valueOf(index++));
                    temp.add(bill.getId());
                    temp.add(bill.getBillNo());
                    switch (bill.getBillType()) {
                    case NONEEDING:
                        tempString = "无";
                        break;
                    case PERSONAL:
                        tempString = "个人";
                        break;
                    case UNIT:
                        tempString = "单位";
                        break;
                    default:
                        tempString = "无";
                        break;
                    }
                    temp.add(tempString);
                    temp.add(bill.getBillTitle());

                    dataList.add(temp);
                }
                // 导出标题列
                String[] rows = new String[] { "序号", "账单号", "发票票号", "发票类型", "发票抬头" };
                // 导出excel文件每列宽度
                int[] style = new int[] { 5, 20, 20, 20, 20 };
                // Excel文件sheet名称
                String sheetName = "发票记录" + DateUtils.getCurrentDate();
                String fileName = "发票记录";
                doExecl(response, fileName, sheetName, dataList, rows, style);
                LogUtils.insertLog("用户导出发票清单", user.getId(), request);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * @Description 通过传入的对象信息集合产生的excel表格<br>
     * @param response
     *            用户响应
     * @param sheetName
     *            excel表名称
     * @param dataList
     *            传入的数据列表
     * @param rows
     *            excel表的列控制，名称
     * @param style
     *            规定列宽等样式
     * @throws Exception
     * @author xujl
     * @date 2016年5月3日
     * @see
     */
    private void doExecl(HttpServletResponse response, String tempName, String sheetName,
                         ArrayList<ArrayList<String>> dataList, String[] rows, int[] style)
        throws Exception {
        // 输出的excel名称为中文，否则发生错误
        String tempFileName = tempName + ".xls";
        String fileName = new String(tempFileName.getBytes("GB2312"), "ISO_8859_1");

        ServletOutputStream fout = response.getOutputStream();
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "filename=" + fileName + "");
        JExcelReport jexcelOutStream = new JExcelReport();
        try {
            jexcelOutStream.excelreport(sheetName, dataList, rows, fout, style);
            fout.flush();
            fout.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    
    /**
     * @Description 根据房间号得到账单列表<br>
     * @param id id
     * @return 跳转画面URL
     * @author xujl
     * @date 2016年4月14日
     * @see
     */
    @RequestMapping(value = "addBillType", method = RequestMethod.GET)
    public String addBillType(Model model, String id) {

        String url = "";
        try {

            model.addAttribute("bid", id);
            url = "property/feebilldetail/addBillType";

        } catch (Exception e) {
        }
        return url;
    }
    
    /**
     * @Description 添加发票
     * @param billType 发票类型
     * @param billTitle 发票抬头
     * @param request 用户的请求
     * @param response 返回的响应
     * @return   更新的结果
     * @author xujl
     * @date 2016年5月19日
     * @see 
     */
    @RequestMapping(value = "saveBillType", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson saveBillType(Model model, String id,  Integer billType, String billTitle,String billNo, HttpServletRequest request,
                                HttpServletResponse response) {
        RequestJson result = new RequestJson();
        final HttpSession session = request.getSession();
        User user = (User)session.getAttribute(RequestConstants.USER_SESSION_ID);

        try {
            FeeBillDetail detail = detailService.selectByPrimaryKey(id);

            detail.setBillType(billType);
            detail.setBillTitle(billTitle);
            detail.setBillNo(billNo);
            detail.setOperator(user.getUsername());
            detail.setOperatorAccount(user.getId());
            detail.setUpdateTime(DateUtils.getDate());

            detailService.updateByPrimaryKey(detail);
            LogUtils.insertLog("用户新增发票信息", user.getId(), request);
            result.setMsg("更新成功");
            result.setSuccess(true);
            
        } catch (Exception e) {
            result.setSuccess(false);
        }
        return result;
    }

}
